package com.hnevc.foodserverapi.controller;


import com.hnevc.foodserverapi.pojo.Comments;
import com.hnevc.foodserverapi.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/foodserver/comment")
public class CommentsController {
    @Autowired
    CommentsService service;

    /**
     * 所有评论列表API
     * 无需传参
     * 返回json对象，数据list
     */
    @PostMapping("/list")
    @ResponseBody
    public Map<String,Object> queryComment(){
        Map<String,Object> map = new HashMap<>();
        List<Comments> list = service.queryComment();
        return getMap(map, list);
    }
    /**
     * 根据foodid查询评论列表API
     * 参数类型int
     * 参数类型json，数据list
     */
    @GetMapping("/list/foodid")
    @ResponseBody
    public Map<String,Object> queryCommentDetails(@PathParam("foodid") int foodid){
        Map<String,Object> map = new HashMap<>();
        List<Comments> list = service.queryCommentDetails(foodid);
        return getMap(map, list);
    }

    /**
     * 发表评论API
     * 参数类型json对象
     * 返回json对象，数据data
     */
    @PostMapping("/add")
    @ResponseBody
    public Map<String,Object> addComment(@RequestBody Comments comments){
        int i = service.addComment(comments);
        Map<String,Object> map = new HashMap<>();
        if (i>0){
            map.put("msg","成功");
            map.put("success",true);
            map.put("data",comments);
        }else {
            map.put("success",false);
            map.put("msg","失败");
        }
        return map;
    }

    /**
     * 根据id查找评论
     * 参数类型 int
     * 返回json对象，数据list
     */
    @GetMapping("/findone")
    @ResponseBody
    public Map<String,Object> queryIdDetails(int id){
        Map<String,Object> map = new HashMap<>();
        List<Comments> list = service.queryIdDetails(id);
        return getMap(map, list);
    }


    //封装map
    private Map<String, Object> getMap(Map<String, Object> map, List<Comments> list) {
        if (!list.isEmpty()){
            map.put("msg","成功");
            map.put("success",true);
            map.put("list",list);
        }else {
            map.put("success",false);
            map.put("msg","失败");
        }
        return map;
    }
}
